<?php

namespace App\Jobs;

use App\Models\WxAttachment;
use App\Wen\Utils\FieldUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UpdateAttachmentTypeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        UpdatePostImgWHJob::dispatch(0)->delay(60);

        $atta = WxAttachment::whereNull('type')->orderBy('id', 'desc')->limit(1000)->get();
        if($atta->isEmpty()){
            return;
        }
        $type = implode('|', FieldUtils::getAttachmentTypes());
        $atta->map(function ($v) use ($type){
            if(strpos($v->path, '.') !== false){
                preg_match('/\.('.$type.')$/', $v->path, $matchs);
                if($matchs && _array_key($matchs, 1, null)){
                    $v->type = $matchs[1];
                    $v->save();
                }
            }else{
                $v->type = '';
                $v->save();
            }
        });
    }
}
